/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <squirrel.h>
#include <sqstdblob.h>
#include <sqstdsystem.h>
#include <sqstdio.h>
#include <sqstdmath.h>
#include <sqstdstring.h>
#include <sqstdaux.h>

#include "Xern/Log.hpp"
#include "Xern/FileSystem.hpp"
#include "Xern/Engine.hpp"
#include "Xern/Exceptions.hpp"
#include "Xern/IScriptModule.hpp"
#include "Xern/PluginRegistrator.hpp"
#include "SquirrelScriptEngine.hpp"
#include "LogHooker.hpp"

#ifdef SQUNICODE
#define scfprintf fwprintf
#define scfopen	_wfopen
#define scvprintf vwprintf
#else
#define scfprintf fprintf
#define scfopen	fopen
#define scvprintf vprintf
#endif

extern "C" {
	int sqopen_Xern(HSQUIRRELVM);
};

namespace XernSquirrel
{
	static PluginRegistrator<SquirrelScriptEngine>
	scriptPlugin("Scripting", "SquirrelScript");

	void printfunc(HSQUIRRELVM v,const SQChar *s,...)
	{
		SQChar msg[1024];
		va_list vl;
		va_start(vl, s);
		scvsprintf(msg, s, vl);
		va_end(vl);

		LogConsole->Write(false, msg);
	}

	SquirrelScriptEngine::SquirrelScriptEngine()
	{
		virtualMachine = NULL;
	}


	SquirrelScriptEngine::~SquirrelScriptEngine()
	{
		if(virtualMachine)
			Shutdown();
	}

	void SquirrelScriptEngine::Initialize()
	{
		// Open the virtual machine.
		virtualMachine = sq_open(1024);

		// Setup the standard library.
		sq_setprintfunc(virtualMachine, printfunc);

		sq_pushroottable(virtualMachine);

		sqstd_register_bloblib(virtualMachine);
		sqstd_register_iolib(virtualMachine);
		sqstd_register_systemlib(virtualMachine);
		sqstd_register_mathlib(virtualMachine);
		sqstd_register_stringlib(virtualMachine);

		sqstd_seterrorhandlers(virtualMachine);

		ioReplace.RegisterLibrary(virtualMachine);

		// Load some modules defined in plugins.
		LoadModules();

		// Load the Xern module.
		sqopen_Xern(virtualMachine);

		// Add hacks.
		void AddHacks();
	}

	void SquirrelScriptEngine::Shutdown()
	{
		if(!virtualMachine)
			return;

		// Remove the log hooker.
		boost::shared_ptr<LogHooker> hook = boost::dynamic_pointer_cast<LogHooker> (LogConsole);
		if(hook)
			hook->Uninstall();

		// Unload the modules.
		UnloadModules();

		// Close the virtual machine
		sq_close(virtualMachine);
		virtualMachine = NULL;
	}

	void SquirrelScriptEngine::RunScript(const std::string &path)
	{
		// Check if the file exists.
		if(!IsFile(path))
			throw XernException("Tried to run inexistent script '" + path + "'");

		// Load the script.
		sq_pushroottable(virtualMachine);
		if(SQ_FAILED(ioReplace.DoFile(virtualMachine, path.c_str(), true)))
			sq_reseterror(virtualMachine);
		else
			sq_pop(virtualMachine, 1); // Ignore the result.
	}

	void SquirrelScriptEngine::AddHacks()
	{
	}

	void SquirrelScriptEngine::LoadModules()
	{
		// Query the 'SquirrelModules' plugin group.
		const PluginGroup *modules =
				Engine::Get().GetPluginRegistry()->QueryGroup("SquirrelModules");
		if(modules)
		{
			// Iterate through each module.
			PluginGroup::const_iterator it = modules->begin();
			for(; it != modules->end(); it++)
			{
				boost::shared_ptr<IScriptModule> module =
						boost::dynamic_pointer_cast<IScriptModule> (it->second);

				// Try to load the module.
				if(module)
					module->Load(virtualMachine, NULL);
			}
		}
	}

	void SquirrelScriptEngine::UnloadModules()
	{
		// Query the 'SquirrelModules' plugin group.
		const PluginGroup *modules =
				Engine::Get().GetPluginRegistry()->QueryGroup("SquirrelModules");
		if(modules)
		{
			// Iterate through each module.
			PluginGroup::const_iterator it = modules->begin();
			for(; it != modules->end(); it++)
			{
				boost::shared_ptr<IScriptModule> module =
						boost::dynamic_pointer_cast<IScriptModule> (it->second);

				// Try to unload the module.
				if(module)
					module->Unload(virtualMachine, NULL);
			}
		}
	}
};
